<?php
namespace app\service;

use think\facade\Config;
use think\facade\Cache;
use app\model\SystemConfig;
use GuzzleHttp\Client;
use Exception;

class AiService
{
    protected $client;
    protected $configs;
    protected $aiHistoryService;
    
    const MAX_HISTORY_MESSAGES = 20; // 触发汇总的消息数量阈值
    const MAX_TOKENS_PER_REQUEST = 4000; // 每次请求的最大token数
    
    public function __construct()
    {
        $this->client = new Client([
            'timeout' => 30,
            'verify' => false
        ]);
        $this->loadConfigs();
        $this->aiHistoryService = new AiHistoryService($this);
    }
    
    protected function loadConfigs()
    {
        $configs = SystemConfig::where('config_group', 'ai')
            ->whereNull('delete_time')
            ->column('config_value', 'config_key');
            
        $this->configs = [
            'type' => $configs['ai_type'] ?? 'deepseek',
            'api_url' => $configs['ai_api_url'] ?? 'https://api.deepseek.com/v1/chat/completions',
            'api_key' => $configs['ai_api_key'] ?? '',
            'model' => $configs['ai_model'] ?? 'deepseek-chat'
        ];

        \think\facade\Log::info('AI配置加载：' . json_encode($this->configs));
    }

    /**
     * 发送流式请求到AI接口
     */
    public function streamChat($messages, callable $callback, ?array $sessionInfo = null)
    {
        if (empty($this->configs['api_key'])) {
            throw new Exception('AI服务密钥未配置');
        }

        // 使用 AiHistoryService 处理历史消息
        if ($sessionInfo !== null) {
            $messages = $this->aiHistoryService->processHistoryAndGenerateReply($messages, $sessionInfo);
        }

        $headers = [
            'Authorization' => 'Bearer ' . $this->configs['api_key'],
            'Content-Type' => 'application/json',
            'Accept' => 'text/event-stream'
        ];
        
        $data = [
            'model' => $this->configs['model'],
            'messages' => $messages,
            'stream' => true,
            'temperature' => 0.7,
            'max_tokens' => self::MAX_TOKENS_PER_REQUEST
        ];
        
        return (new AiStreamHandler($this->client))->handle($this->configs['api_url'], $headers, $data, $callback);
    }

    /**
     * 检查字符串是否为有效的JSON
     */
    protected function isValidJson($string) {
        if (empty($string)) {
            return false;
        }
        try {
            json_decode($string, true);
            return json_last_error() === JSON_ERROR_NONE;
        } catch (Exception $e) {
            return false;
        }
    }

    /**
     * 获取配置信息
     */
    public function getConfigs(): array
    {
        return $this->configs;
    }

    /**
     * 获取HTTP客户端
     */
    public function getClient(): Client
    {
        return $this->client;
    }
} 